<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\BaseController;
use app\service\GoodsService;
use app\service\InnerPurchaseService;
use app\service\UserService;
use think\facade\Validate;
use think\Request;

class StoreInnerController extends BaseController
{
  /**
   * 获取门店内部采购列表
   * @return \think\Response
   */
  public function index(Request $request){
    $page = $request->param('page', 1);
    $pageSize = $request->param('pageSize', env('pager.default.size'));
    $houseSell = $request->param('houseSell', '');
    $status = $request->param('status', []);
    $base = $request->param('base', []);
    $purEnd = $request->param('purEnd', '');
    $purStart = $request->param('purStart', '');
    $groupId = $request->param('groupid', 0);
    $purStart = $purStart ? date('Y-m-d', strtotime($purStart)) : '';
    $purEnd = $purEnd ? date('Y-m-d', strtotime($purEnd) + (24 * 60 * 60)) : '';

    $conditions = [];
    if($base){
      $conditions[] = ['base', $base, 'IN'];
    }
    if ($status) {
      $conditions[] = ['status', $status, 'IN'];
    }
    if ($houseSell !== '') {
      $conditions[] = ['house_sell', $houseSell, '='];
    }
    if ($purStart) {
      $conditions[] = ['purchase_time', $purStart, '>='];
    }
    if ($purEnd) {
      $conditions[] = ['purchase_time', $purEnd, '<'];
    }
    if ($groupId == 3) {
      $order = ['purchase_time' => 'DESC', 'base' => 'ASC', 'id' => 'DESC'];
    } else {
      $order = ['base' => 'ASC', 'purchase_time' => 'DESC', 'id' => 'DESC'];
    }
    $list = InnerPurchaseService::getInstance()->getInnerOrderByCondition($conditions, $order);
    // base
    $baseList = UserService::getModel()
      ->where('groupid', '=', '8')
      ->select()
      ->toArray();
    $baseList = array_column($baseList, 'basename', 'base');
    foreach ($list as &$value) {
      $value['basename'] = isset($baseList[$value['base']]) ? $baseList[$value['base']] : '';
    }
    // 分页
    $count = count($list); //总条数
    $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
    $pager = [
      'totalCount' => $count,
      'pageSize' => intval($pageSize),
      'currPage' => intval($page),
      'totalPage' => intval($count/$pageSize)+1
    ];
    $data = array_slice($list, $start, intval($pageSize));
    return $this->send200ResponseWithPager($data,$pager);
  }

  /**
   * 根据编号获取内部采购详情
   * @return \think\Response
   */
  public function read($id){
    if (!$id) {
      return $this->send400Response('ID不能为空');
    }
    $order = InnerPurchaseService::getModel()
      ->find($id)
      ->toArray();
    $conditions[] = ['i.inner_order_id', $id, '='];
    $inner = InnerPurchaseService::getInstance()->getInnerJoinGoods($conditions);
    $order['list'] = $inner;
    return $this->send200Response($order);
  }

  /**
   * 新增内部采购
   * @return \think\Response
   */
  public function save(Request $request){
    $data['data'] = $request->param('data', []);
    $data['base'] = $request->param('base', '');
    $data['purchase'] = $request->param('purchase_time', '');
    $data['type'] = $request->param('type', '');

    $validate = Validate::rule([
      'data' => 'require',
      'base' => 'require',
      'purchase' => 'require',
      'type' => 'require'
    ])->message([
      'data.require' => '缺少data参数',
      'base.require' => '缺少base参数',
      'purchase.require' => '缺少purchase_time参数',
      'type.require' => '缺少type参数'
    ]);
    if (!$validate->check($data)) {
      return $this->send400Response($validate->getError());
    }
//    if ($data['purchase']) {
//      return $this->send400Response('日期不得为空');
//    }
    $result = InnerPurchaseService::getInstance()->createMultiInner($data);
    if (!$result['status']) {
      return $this->send400Response($result['msg']);
    }
    return $this->send200Response('ok');
  }

  /**
   * 修改内部采购单
   * @return \think\Response
   */
  public function update(Request $request, $id){
    $data = $request->param('data', []);
    $purchase = $request->param('purchase_time', '');
    $type = $request->param('type', 1);
    if (!$data) {
      return $this->send400Response('data不能为空');
    }
    if (!$purchase) {
      return $this->send400Response('purchase_time不能为空');
    }
    $result = InnerPurchaseService::getInstance()->updateMultiInner($id, $purchase, $data, $type);
    if (!$result['status']) {
      return $this->send400Response($result['msg']);
    }
    return $this->send200Response('ok');
  }

  /**
   * 内部采购审批
   * @return \think\Response
   */
  public function check(Request $request){
    $check = $request->param('check', '');
    $orderId = $request->param('orderId', '');
    $comment = $request->param('comment', '');
    if ($check === '') {
      return $this->send400Response('check必填');
    }
    if ($orderId === '') {
      return $this->send400Response('orderId必填');
    }
    $result = InnerPurchaseService::getInstance()->checkInner($orderId, $check, $comment);
    if ($result['status']) {
      return $this->send200Response('ok');
    }
    return $this->send400Response($result['msg']);
  }

  /**
   * 内部采购删除
   * @return \think\Response
   */
  public function delete($id){
    $result = InnerPurchaseService::getInstance()->deleteStoreInner($id);
    if ($result['status']) {
      return $this->send200Response('ok');
    }
    return $this->send400Response($result['msg']);
  }

  /**
   * 根据编号获取打印详情
   * @return \think\Response
   */
  public function print(Request $request){
    $id = $request->param('id','');
    $conditions = [
      ['o.id', $id, '='],
      ['o.status', 1, '=']
    ];
    $order = InnerPurchaseService::getInstance()->getInnerOrderJoinBase($conditions);
    $inner = InnerPurchaseService::getInstance()->getInnerJoinGoods([['i.inner_order_id', $id, '=']]);
    // 分类
    $categoryGroup = [
      1 => 'fifth', 2 => 'fifth', 3 => 'first',
      4 => 'third', 5 => 'fifth', 6 => 'forth',
      7 => 'first', 8 => 'third', 9 => 'fifth',
      10 => 'fifth', 11 => 'fifth', 12 => 'first',
      13 => 'second'];
    $goodsSpecial = ['腌制虾仁' => 'first', '花生油' => 'forth', '调和油' => 'forth'];
    $first = [];
    $second = [];
    $third = [];
    $forth = [];
    $fifth = [];
    foreach ($inner as $value) {
      $catGroup = $categoryGroup[$value['category_id']];
      if (isset($goodsSpecial[$value['good_name']])) {
        $catGroup = $goodsSpecial[$value['good_name']];
      }
      array_push($$catGroup, $value);
    }
    $catList = [
      0 => 'first',
      1 => 'second',
      2 => 'third',
      3 => 'forth',
      4 => 'fifth'
    ];
    $firstAll = [];
    $secondAll = [];
    $thirdAll = [];
    $forthAll = [];
    $fifthAll = [];
    $firstLast = [];
    $secondLast = [];
    $thirdLast = [];
    $forthLast = [];
    $fifthLast = [];
    $firstNew = [];
    $secondNew = [];
    $thirdNew = [];
    $forthNew = [];
    $fifthNew = [];
    $data = [];
    // 处理导出分类
    foreach ($catList as $v) {
      $t = $v.'All';
      $l = $v.'Last';
      $n = $v.'New';
      $$t = array_chunk($$v,12);
      $$l = array_pop($$t);
      if ($$l && count($$l) < 12) {
        for ($i=0;$i<12;$i++) {
          $add = [];
          if (isset($$l[$i])) {
            array_push($$n, $$l[$i]);
          } else {
            $add = [
              'category_name' => '',
              'good_name' => '',
              'count' => '',
              'unit' => '',
              'comment' => ''
            ];
            array_push($$n, $add);
          }
        }
      } else {
        $$n = $$l;
      }
      if ($$n) {
        $data[] = $$n;
      }
    }
    $result = [
      'data' => $data,
      'info' => $order ? $order[0] : []
    ];
    return $this->send200Response($result);
  }
}